package request

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	StatusOK                  = 0
	StatusBadRequest          = 4000
	StatusInternalServerError = 5000
)

// CommonResponse ...
type CommonResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

func request(ctx *gin.Context, httpCode, innerCode int, message string, data ...interface{}) {
	resp := CommonResponse{
		Code:    innerCode,
		Message: message,
	}
	if len(data) > 0 {
		resp.Data = data[0]
	}
	ctx.JSON(httpCode, resp)
}

// ParamError ...
func ParamError(ctx *gin.Context) {
	request(ctx, http.StatusBadRequest, StatusBadRequest, "param error")
}

// ServerError ...
func ServerError(ctx *gin.Context, err error) {
	request(ctx, http.StatusInternalServerError, StatusInternalServerError, err.Error())
}

// Fail ...
func Fail(ctx *gin.Context, httpCode, innerCode int, message string, data ...interface{}) {
	request(ctx, httpCode, innerCode, message, data...)
}

// Success ...
func Success(ctx *gin.Context, data ...interface{}) {
	request(ctx, http.StatusOK, StatusOK, "success", data...)
}
